<?php

declare(strict_types=1);
/**
 * This file is part of bearing-web.
 *
 * @link     https://www.bearing.cn/
 * @contact  tech@bearing.cn
 * @license  https://gitee.com/cppo/bearing_web/-/blob/master/README.md
 */

namespace frontend\controllers;

use yii\base\DynamicModel;
use yii\elasticsearch\Exception;
use yii\helpers\ArrayHelper;

class ProductSearchController extends BaseController
{
    protected array $aggField = [];


    public function actions(): array
    {
        return ArrayHelper::merge(
            parent::actions(),
            [
                'index' => [
                    'dataFilter' => [
                        'class' => 'yii\data\ActiveDataFilter',
                        'searchModel' => function () {
                            return $this->getDynamicModel();
                        },
                    ],
                ],
            ]
        );
    }

    /**
     * @return array|array[]
     * @throws Exception
     */
    public function actionFilter(): array
    {
        $filter = \Yii::$app->request->get('filter');
        $model = (new $this->modelClass())::find();
        if ($filter) {
            $model->andFilterWhere($filter);
        }
        foreach ($this->aggField as $agg) {
            $model->addAggregate($agg, ['terms' => ['field' => $agg]]);
        }
        $ret = $model->limit(0)->search();
        $arr = $ret['aggregations'] ?? [];
        $items = [];
        foreach ($arr as $key => $value) {
            $buckets = $value['buckets'] ?? [];
            if ($buckets) {
                $items[$key] = $buckets;
            }
        }
        return $items;
    }

    protected function getDynamicModel(): DynamicModel
    {
        $model = new DynamicModel($this->getDynamicModelAttributes());
        $fieldRule = $this->getFieldRuleList();
        foreach ($this->aggField as $field) {
            $model->addRule($field, $fieldRule[$field]??'string');
        }
        return $model;
    }

    protected function getDynamicModelAttributes(): array
    {
        $attributes = [];
        foreach ($this->aggField as $field) {
            $attributes[$field] = null;
        }
        return $attributes;
    }


    /**
     * 获取字段类型规则
     * @return string[]
     */
    protected function getFieldRuleList(): array
    {
        return ['cate_id'=>'integer'];
    }
}
